﻿using System;
using System.Collections.Generic;
using System.Text;

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Tools
{
    using System;
    using System.Configuration;
    using System.IO;
    using System.Text;

    public class LogHelper : IDisposable
    {
        private static string _logPath;
        private static int _logSize = 0x2800;
        private static int _maxCount = 10;
        private static string _logSuffix = "log";
        private static int _linecharCount = 120;
        private static FileStream _newFS = null;
        private static FileInfo _openFile = null;
        private static StreamWriter _sw = null;
        private bool disposed;

        public void Close()
        {
            this.Dispose();
        }

        private static void CreateMatchFolder(string path)
        {
            if (!Directory.Exists(_logPath))
            {
                Directory.CreateDirectory(path);
            }
        }

        private static void CreateNewLog(string logFile)
        {
            if (!File.Exists(logFile))
            {
                using (_newFS = new FileStream(logFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    _sw = new StreamWriter(_newFS, Encoding.UTF8);
                    _sw.WriteLine("文件创建时间:{0}", DateTime.Now.ToString());
                    _sw.WriteLine("文件最大记录大小:{0}KB(与实际可能会有出入)", _logSize);
                    _sw.WriteLine(_sw.NewLine);
                    _newFS.Flush();
                    _sw.Dispose();
                    _sw = null;
                }
            }
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (_sw != null)
                    {
                        _sw.Close();
                        _sw.Dispose();
                        _sw = null;
                    }
                    if (_newFS != null)
                    {
                        _newFS.Close();
                        _newFS.Dispose();
                        _newFS = null;
                    }
                    if (_openFile != null)
                    {
                        _openFile = null;
                    }
                }
                this.disposed = true;
            }
        }

        ~LogHelper()
        {
            this.Dispose(false);
        }

        private static string FindCanWriteFileName(string path, string name)
        {
            string str = string.Empty;
            for (int i = 1; i <= MaxCount; i++)
            {
                str = string.Format("{0}/{2}-{1}", path, name, i);
                if (!File.Exists(str) || ((new FileInfo(str).Length / 0x400L) < _logSize))
                {
                    return str;
                }
            }
            return str;
        }

        public static bool SaveErrorLog(string title, String errMsg)
        {
            string[] message = new string[] { errMsg };
            return WriteLog(LogType.ApplicationError, _logPath, title, LogWarnLevel.Error, message);
        }

        public static bool SaveErrorLog(string title, Exception ex)
        {
            string[] message = new string[] { ex.Message };
            return WriteLog(LogType.ApplicationError, _logPath, title, LogWarnLevel.Error, message);
        }

        public static bool SaveErrorLog(string title, Exception ex, bool autoLinefeed)
        {
            string[] message = SplitString(ex.Message);
            return WriteLog(LogType.ApplicationError, _logPath, title, LogWarnLevel.Error, message);
        }

        public static bool SaveLog(string title, string message)
        {
            string[] textArray1 = new string[] { message };
            return WriteLog(LogType.Common, _logPath, title, LogWarnLevel.message, textArray1);
        }

        public static bool SaveLog(LogType logType, string title, string message)
        {
            string[] textArray1 = new string[] { message };
            return WriteLog(logType, _logPath, title, LogWarnLevel.message, textArray1);
        }

        public static bool SaveLog(LogType logType, string title, string message, bool autoLinefeed)
        {
            string[] strArray = SplitString(message);
            return WriteLog(logType, _logPath, title, LogWarnLevel.message, strArray);
        }

        private static string[] SplitString(string message)
        {
            int length = message.Length;
            int num2 = (int)Math.Ceiling((double)(((double)length) / ((double)_linecharCount)));
            string[] strArray = new string[num2];
            for (int i = 0; i < num2; i++)
            {
                if (length < _linecharCount)
                {
                    strArray[i] = message;
                }
                else if ((length - (i * _linecharCount)) < _linecharCount)
                {
                    strArray[i] = message.Substring(i * _linecharCount, length - (i * _linecharCount));
                }
                else
                {
                    strArray[i] = message.Substring(i * _linecharCount, _linecharCount);
                }
            }
            return strArray;
        }

        private static bool WriteLog(LogType type, string path, string title, LogWarnLevel level, params string[] message)
        {
            string str = string.Format("{0}.{1}", DateTime.Now.ToString("yyyy-MM-dd"), _logSuffix);
            if (type != LogType.SysError)
            {
                str = Enum.Parse(typeof(LogType), type.GetHashCode().ToString()).ToString().Trim() + string.Format("{0}.{1}", DateTime.Now.ToString("yyyy-MM-dd"), _logSuffix);
            }
            string str2 = string.Format("{0}/{1}", path, str);
            if (!File.Exists(str2))
            {
                CreateNewLog(str2);
            }
            if ((_openFile == null) || (_sw == null))
            {
                _openFile = new FileInfo(str2);
                if ((_openFile.Length / 0x400L) > _logSize)
                {
                    str2 = FindCanWriteFileName(path, str);
                    CreateNewLog(str2);
                    _openFile = new FileInfo(str2);
                }
                _newFS = _openFile.Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                _sw = new StreamWriter(_newFS);
            }
            if (_sw == null)
            {
                return false;
            }
            _sw.WriteLine("================{0}=================", title);
            _sw.WriteLine("记录时间:{0}  等级:{1}", DateTime.Now.ToString(), (level == LogWarnLevel.message) ? "message" : "error");
            _sw.WriteLine();
            if (message != null)
            {
                foreach (string str3 in message)
                {
                    _sw.WriteLine(str3);
                }
            }
            _sw.WriteLine();
            _sw.Flush();
            return true;
        }

        public static string LogPath
        {
            get
            {
                return _logPath;
            }
            set
            {
                if (string.IsNullOrEmpty(_logPath))
                {
                    _logPath = SysConstant.AppStartPath + "/Log";
                }
                CreateMatchFolder(_logPath);
            }
        }

        public static int LogSize
        {
            get
            {
                return _logSize;
            }
            set
            {
                _logSize = value;
            }
        }

        public static int MaxCount
        {
            get
            {
                return _maxCount;
            }
            set
            {
                _maxCount = value;
            }
        }

        public static string LogSuffix
        {
            get
            {
                return _logSuffix;
            }
            set
            {
                _logSuffix = value;
            }
        }

        public static int LineCharCount
        {
            get
            {
                return _linecharCount;
            }
            set
            {
                _linecharCount = value;
            }
        }
    }

    public enum LogType
    {
        ApplicationError = -1,
        SysError = 0,
        Common = 1,
        Setup = 2,
        Login = 3,
        Logout = 4,
        UnKnown = 5,
        None = 6
    }
    public enum LogWarnLevel
    {
        message = 1,
        Error = 2
    }
}

